const fs = require("fs");
const path = require("path");
const JmxExecutor = require("./JmxExecutor");
const { JtlParser, JtlAnalyzer } = require("../jtlAnalysis");

class JmxRuntime {

    /**
     * 
     * @param {JmxExecutor} jmxExecutor 
     * @param {string} jmxFilePath 
     * @param {number} threadNumber 
     * @param {number} duration 
     * @param {string} jtlPath 
     */
    constructor(jmxExecutor, jmxFilePath, threadNumber, duration, jtlPath) {
        if (!fs.existsSync(jmxFilePath)) {
            throw new Error(`JMX 文件不存在: ${jmxFilePath}`);
        }
        this.jmxExecutor = jmxExecutor;
        this.jmxFilePath = jmxFilePath;
        this.testPlanName = path.parse(this.jmxFilePath).name;
        this.threadNumber = threadNumber;
        this.duration = duration;
        this.jtlPath = jtlPath;
        this.testResults = [];
    }

    get round() {
        return this.testResults.length;
    }

    get jtlFilePath() {
        return path.resolve(this.jtlPath, `${String(this.round).padStart(3, "0")}_${this.testPlanName}_${this.threadNumber}_${this.duration}.jtl`);
    }

    async run() {
        await this.jmxExecutor.execute(this);
        const jtlFilePath = this.jtlFilePath;
        if (!fs.existsSync(jtlFilePath)) {
            throw new Error(`JTL 文件不存在: ${jtlFilePath}`);
        }
        const jtlParser = new JtlParser(jtlFilePath);
        const jtlData = await jtlParser.parse();
        const jtlAnalyzer = new JtlAnalyzer(jtlData);
        this.testResults.push(jtlAnalyzer.analyze().baseReport);
        return this.testResults;
    }

}

module.exports = JmxRuntime;